package com.bwie.service.Impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.mapper.OrderDetailMapper;
import com.bwie.mapper.OrderRecordMapper;
import com.bwie.mapper.ProdInfoMapper;
import com.bwie.poi.ExcelUtil;
import com.bwie.pojo.OrderDetail;
import com.bwie.pojo.OrderRecord;
import com.bwie.pojo.ProdInfo;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.OrderMapper;
import com.bwie.pojo.Order;
import com.bwie.service.OrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService{
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private ProdInfoMapper prodInfoMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderRecordMapper orderRecordMapper;
    @Override
    public R getOrderList(PageInfoVo pageInfoVo) {
        Page<Order> orderPage = new Page<>(pageInfoVo.getPageNum(),pageInfoVo.getPageSize());
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(pageInfoVo.getKeyWord())){
            orderQueryWrapper.lambda().eq(Order::getProdInfo,pageInfoVo.getKeyWord())
                    .or().eq(Order::getOrderId,pageInfoVo.getKeyWord());
        }
        if(ObjectUtils.isNotEmpty(pageInfoVo.getProdStatus())){
            orderQueryWrapper.lambda().eq(Order::getOrderStatus,pageInfoVo.getProdStatus());
        }
        if(ObjectUtils.isNotEmpty(pageInfoVo.getTypeId())){
            orderQueryWrapper.lambda().eq(Order::getOrderType,pageInfoVo.getTypeId());
        }
        Page<Order> orderPage1 = orderMapper.selectPage(orderPage, orderQueryWrapper);
        for (Order record : orderPage1.getRecords()) {
            List<String> imageList = orderMapper.selectImageList(record.getOrderId());
            List<String> images = new ArrayList<>();
            if(ObjectUtils.isNotEmpty(imageList) && imageList.size()>0){
                for (String s : imageList) {
                    if(StringUtils.isNotEmpty(s)){
                        List<String> strings = JSON.parseArray(s, String.class);
                        images.addAll(strings);
                    }
                }
            }
            record.setImageList(images);
        }
        return R.OK(orderPage1);
    }

    @Override
    public R deleteOrderBatch(List<Integer> ids) {
        orderMapper.deleteBatchIds(ids);
        orderMapper.delete(
                new QueryWrapper<Order>().lambda().eq(Order::getOrderId,ids)
        );
        return R.OK();
    }

    @Override
    public R getExel() {
        ExcelUtil<Order> orderExcelUtil = new ExcelUtil<>(Order.class);
        List<Order> list = this.list();
        orderExcelUtil.exportExcel(response,list,"订单列表");
        return R.OK();
    }

    @Override
    public R getProdInfoList() {
        List<ProdInfo> prodInfos = prodInfoMapper.selectList(null);
        return R.OK(prodInfos);
    }

    @Override
    public R addProdInfoList(List<ProdInfo> prodInfoList) {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            return R.ERROR(500,"请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        String userName = body.get("userName", String.class);
        BigDecimal bigDecimal = new BigDecimal("0");
        StringBuilder stringBuilder = new StringBuilder();
        RLock lock = redissonClient.getLock("pageInfo-lock");
        try {
            lock.lock();
            for (ProdInfo prodInfo : prodInfoList) {
                ProdInfo prodInfo1 = prodInfoMapper.selectById(prodInfo.getInfoId());
                if(prodInfo.getBuyNum() > prodInfo1.getProdStock()){
                    throw new RuntimeException("库存不足");
                }
                prodInfo1.setProdStock(prodInfo1.getProdStock() - prodInfo.getBuyNum());
                prodInfoMapper.updateById(prodInfo1);
                bigDecimal = bigDecimal.add(prodInfo.getProdPrice().multiply(new BigDecimal(prodInfo.getBuyNum())));
                stringBuilder.append(prodInfo.getProdName());
                if(stringBuilder.length()>0){
                    stringBuilder.append(",");
                    stringBuilder.append(prodInfo.getProdName());
                }else{
                    stringBuilder.append(prodInfo.getProdName());
                }
            }
        } finally {
            lock.unlock();
        }
        Order order = new Order();
        long l = IdUtil.getSnowflake(1, 1).nextId();
        order.setOrderNo(""+l);
        order.setOrderType(1);
        order.setOrderStatus(0);
        order.setOrderAmount(bigDecimal);
        order.setProdInfo(stringBuilder.toString());
        order.setUserId(userId);
        order.setUpdateBy(userName);
        order.setCreateBy(userName);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        orderMapper.insert(order);
        for (ProdInfo prodInfo : prodInfoList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getOrderId());
            orderDetail.setBuyNum(prodInfo.getBuyNum());
            orderDetail.setProdId(prodInfo.getProdId());
            orderDetail.setBuyPrice(prodInfo.getProdPrice());
            orderDetail.setInfoId(prodInfo.getInfoId());
            orderDetail.setCreateBy(userName);
            orderDetail.setCreateTime(new Date());
            orderDetailMapper.insert(orderDetail);
        }
        OrderRecord orderRecord = new OrderRecord();
        orderRecord.setOrderId(order.getOrderId());
        orderRecord.setOptRecord("用户创建订单");
        orderRecord.setCreateTime(new Date());
        orderRecord.setCreateBy(userName);
        orderRecord.setUpdateBy(userName);
        orderRecord.setUpdateTime(new Date());
        orderRecordMapper.insert(orderRecord);
        return R.OK();
    }
}
